package test;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用中文地址，解析出省市区的code。做法和C端用户添加快递地址功能一样。
 *
 * @author zhangrui
 * @version 1.0.0.1
 * @description:
 * @createDate 2021-7-20
 */
public class AddressRegexServiceImpl {

    private Logger logger = LoggerFactory.getLogger(AddressRegexServiceImpl.class);

    private static final String BEIJING = "北京";
    private static final String SHANGHAI = "上海";
    private static final String CHONGQING = "重庆";
    private static final String TIANJIN = "天津";

    /**
     * 直辖市比较特殊
     */
    private static final List<String> SPECIAL_LIST = new ArrayList<>();
    static {
        SPECIAL_LIST.add(BEIJING);
        SPECIAL_LIST.add(SHANGHAI);
        SPECIAL_LIST.add(CHONGQING);
        SPECIAL_LIST.add(TIANJIN);
    }

    public static void main(String[] args) {
        String address = "重庆市沙坪坝区凤中路鸣沙街西物市场101-1-3" ;
        String regex = "(?<province>[^省]+自治区|.*?省|.*?行政区|上海|北京|天津|重庆.*?市)?(?<city>[^市]+自治州|.*?地区|.*?行政单位|.+盟|市辖区|.*?市|.*?县)?(?<area>[^县]+县|.+区|.+市|.+旗|.+海域|.+岛)?(?<town>[^区]+区|.+镇)?(?<village>.*)";
        //(?<province>[^省]+自治区|.*?省|.*?行政区|.*?市)?表示一个模块 最后的问号表示可以为空
        Matcher m = Pattern.compile(regex).matcher(address);
        String province, city, area;
        if (m.find()) {
            province = m.group("province");
            city = m.group("city");
            area = m.group("area");
            if (StringUtils.isNotBlank(province) && StringUtils.isNotBlank(area)) {
                for (String municipality : SPECIAL_LIST) {
                    if (province.contains(municipality)) {
                        province = municipality;
                        city = province + "市";
                        area = area.replace(city, "");
                        break;
                    }
                }
            }
            System.out.println(province);
            System.out.println(city);
            System.out.println(area);
        }
    }

}
